import '@amap/amap-jsapi-types';
import { useState, useEffect } from 'react';
import { message } from 'antd';
import { debounce } from 'lodash';
import gcjEncrypt from '@/utils/handle-location';
import styles from './style.less';
import { ProFormDateTimePicker } from '@ant-design/pro-components';
import { getDeviceCoordinate, getDeviceTrack } from '../service';

let map: AMap.Map;
let pathSimplifierIns: any;
let navigator: any;
/**
 * @see https://lbs.amap.com/api/amap-ui/reference-amap-ui/mass-data/pathsimplifier#PathNavigator
 * @param PathSimplifier
 */

export default (props: { deviceSn: string }) => {
  // @ts-ignore
  const { AMap, AMapUI } = window;
  const { deviceSn } = props;
  const [startTime, setStartTime] = useState<string>('');
  const [endTime, setEndTime] = useState<string>('');
  const initPage = (PathSimplifierClazz: any, newMap: AMap.Map) => {
    // 创建组件实例
    pathSimplifierIns = new PathSimplifierClazz({
      zIndex: 100,
      map: newMap, // 所属的地图实例
      // 返回轨迹数据中的节点坐标信息，[AMap.LngLat, AMap.LngLat...] 或者 [[lng|number,lat|number],...]
      getPath: (pathData: any) => pathData.path,
      getHoverTitle: (pathData: any, pathIndex: number, pointIndex: number) => {
        // 返回鼠标悬停时显示的信息
        if (pointIndex >= 0) {
          // 鼠标悬停在某个轨迹节点上
          return `${pathData.name}，点:${pointIndex + 1}/${pathData.path.length}`;
        }
        // 鼠标悬停在节点之间的连线上
        return `${pathData.name}，点数量${pathData.path.length}`;
      },
      renderOptions: {
        // 轨迹线的样式
        pathLineStyle: {
          strokeStyle: 'red',
          lineWidth: 5,
          dirArrowStyle: true,
        },
        pathNavigatorStyle: {
          initRotateDegree: 0,
          width: 16,
          height: 16,
          autoRotate: true,
          lineJoin: 'round',
          content: 'defaultPathNavigator',
          fillStyle: '#087EC4',
          strokeStyle: '#116394',
          lineWidth: 1,
          pathLinePassedStyle: {
            lineWidth: 3,
            strokeStyle: '#0c88d2',
            borderWidth: 2,
            borderStyle: '#eeeeee',
            dirArrowStyle: false,
          },
        },
      },
    });
  };
  const getPatrolDeviceTrack = debounce(async () => {
    if (pathSimplifierIns) {
      if (!deviceSn) return;
      if (!startTime || !endTime) {
        return;
      }

      const timeDiff = new Date(endTime).getTime() - new Date(startTime).getTime();
      if (timeDiff <= 0) {
        message.error({ key: 'query_track', content: '开始时间不能大于结束时间' });
        return;
      }
      if (timeDiff > 12 * 60 * 60 * 1000) {
        message.error({ key: 'query_track', content: '时间跨度不能大于12小时哦' });
        return;
      }

      const ret = await getDeviceTrack(deviceSn, startTime, endTime);
      if (ret.success) {
        if (ret.data && ret.data.length > 0) {
          const coordinateArray = ret.data.map((v) => {
            const gcjCoordinate = gcjEncrypt(v[1], v[0]);
            return [gcjCoordinate.lon, gcjCoordinate.lat];
          });
          // if (navigator) navigator.destroy();
          pathSimplifierIns.setData([
            {
              name: `巡检设备 ${deviceSn}`,
              path: coordinateArray,
            },
          ]);
          navigator = pathSimplifierIns.createPathNavigator(0, {
            loop: false,
            speed: 500,
            /* pathNavigatorStyle: {
              strokeStyle: '#0c88d2',
              lineWidth: 3,
              borderStyle: '#eeeeee',
              borderWidth: 2,
              dirArrowStyle: true,
            }, */
          });
          navigator.start();
        } else {
          message.warn({ key: 'query_track', content: '无有效数据' });
        }
      } else {
        message.error({ key: 'query_track', content: `获取巡检路线错误: ${ret.errorMessage}` });
      }
    }
  }, 500);
  useEffect(() => {
    map = new AMap.Map('amap_container', {
      zoom: 15,
      resizeEnable: true,
    });
    if (AMapUI) {
      AMapUI.load(['ui/misc/PathSimplifier'], (PathSimplifierClass: any) => {
        if (!PathSimplifierClass?.supportCanvas) {
          // eslint-disable-next-line no-alert
          alert('当前环境不支持 Canvas！');
          return;
        }
        initPage(PathSimplifierClass, map);
      });
    }
  }, [AMap.Map, AMapUI]);

  useEffect(() => {
    getPatrolDeviceTrack();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [deviceSn, startTime, endTime]);
  useEffect(() => {
    if (deviceSn) {
      getDeviceCoordinate(deviceSn).then((res) => {
        if (res.data[0] && res.data[1]) {
          const gcjCoordinate = gcjEncrypt(res.data[1], res.data[0]);
          map.setCenter([gcjCoordinate.lon, gcjCoordinate.lat]);
          // map.setZoom(15);
          //@ts-ignore
          const marker = new AMap.Marker({
            icon: '/marks/1_red_32.svg',
            position: [gcjCoordinate.lon, gcjCoordinate.lat],
            title: '当前巡检车位置',
          });
          map.clearMap();
          map.add(marker);
        } else {
          message.error({ key: 'query_track', content: '当前巡检车位置无效' });
        }
      });
    }
  }, [AMap.Marker, deviceSn]);

  return (
    <div
      style={{
        position: 'relative',
        padding: 5,
        margin: -21,
        background: '#fff',
      }}
    >
      <div id="amap_container" style={{ width: '100%', height: '70vh' }} />
      <div className={styles.select}>
        <ProFormDateTimePicker
          width="xl"
          label="选择开始时间"
          name="startTime"
          fieldProps={{
            onChange: (val) => setStartTime(val?.toString() || ''),
            style: {
              width: '100%',
            },
          }}
        />
        <ProFormDateTimePicker
          width="xl"
          label="选择结束时间"
          name="endTime"
          fieldProps={{
            onChange: (val) => setEndTime(val?.toString() || ''),
            style: {
              width: '100%',
            },
          }}
        />
      </div>
    </div>
  );
};
